//
//  NDProductDetailView.swift
//  NyamanDana
//
//  Created by 李永彬 on 2025/10/17.
//

import SwiftUI

struct NDProductDetailView: View, TitledView {
    var productId: Int
    var navigationTitle: String = localizedString("Product details")
    
    @StateObject private var viewModel = NDOrderDetailViewModel()
    @Environment(\.navigationManager) var navManager
    @StateObject private var refreshController = NDScrollViewRefreshController()
    @Environment(\.presentationMode) var presentationMode
    @State private var isWebViewPushing = false
    
    var body: some View {
        let navigationConfig = NavigationConfig(
            title: navigationTitle,
            showSystemBackButton: true
        )
        
        NDBaseContentView(navigationConfig: navigationConfig) {
            VStack {
                NDRefreshableScrollView(
                    refreshController: refreshController,
                    onRefresh: {
                        viewModel.productId = productId
                        viewModel.loadProductDetailData()
                    }
                ) {
                    ScrollView {
                        VStack(spacing: 20) {
                            // 原始顶部视图
                            NDProductDetailTopView(
                                productInfo: viewModel.productInfo,
                                isLoading: viewModel.isLoading
                            )
                            .padding(.horizontal, 5)
                            
                            VStack(spacing: 0) {
                                ForEach(Array(viewModel.authItems.enumerated()), id: \.offset) { index, authItem in
                                    ProductStepView(stepNumber: String(format: "%02d", index + 1),
                                                    title: authItem.pitister ?? "",
                                                    description: authItem.authType.displayText,
                                                    showDashLine: index != viewModel.authItems.count - 1) {
                                        
                                        if authItem.isCompleted {
                                            AnyView(getCompletedButton(title: authItem.upon ?? ""))
                                        } else {
                                            AnyView(getGoAndVerifyButton(title: authItem.upon ?? ""))
                                        }
                                    }
                                                    .onTapGesture {
                                                        if authItem.isCompleted {
                                                            guard let cernious = authItem.cernious else {
                                                                return
                                                            }
                                                            
                                                            viewModel.toNavTitle = authItem.pitister ?? ""
                                                            if let authType = AuthType(rawValue: cernious) {
                                                                self.goToCorrectVC(with: authType, isCompleted: true)
                                                            }
                                                        } else {
                                                            self.nextStepAction()
                                                        }
                                                    }
                                }
                            }
                        }
                        .frame(maxHeight: .infinity)
                        .padding(.bottom, 5)
                    }
                    .padding(.bottom, 2)
                }
                
                Button(action: nextStepAction) {
                    Text(localizedString("Get Money"))
                        .frame(maxWidth: .infinity)
                        .font(.system(size: 18, weight: .bold))
                        .foregroundColor(Color(hex: "#FFFFFF"))
                        .padding(.horizontal, 15)
                        .padding(.vertical, 10)
                        .frame(height: 48)
                        .background(Color(hex: "#271F24"))
                        .clipShape(Capsule())
                        .contentShape(Rectangle())
                        .padding(.bottom, 10)
                }
                .padding(.horizontal, 16)
            }
        }
        .onAppear(perform: {
            refreshController.beginRefreshing()
            
            if viewModel.nextStepAction == nil {
                viewModel.setNextStepNotification {
                    setNextStepNotification()
                }
            }

            if viewModel.followOrderAction == nil {
                viewModel.setFollowOrderAction { followModel in
                    if let followModel = followModel {
                        goToWebView(followModel.trigesim ?? "")
                        viewModel.cleanup()
                    }
                }
            }
            
            viewModel.requestAddressData()
        })
        .onChange(of: viewModel.isLoading) { isLoading in

            DispatchQueue.main.async {
                if isLoading {
                    NDProgressHUD.show()
                } else {
                    NDProgressHUD.dismiss()
                    refreshController.endRefreshing()
                }
            }
        }
        .onChange(of: viewModel.errorMessage) { msg in
            NDProgressHUD.showInfo(msg)
        }
        .onChange(of: presentationMode.wrappedValue.isPresented) { isPresented in
            if !isPresented {
                // 当页面被 pop 时清理
                viewModel.cleanup()
            }
        }
        .setViewIdentifier(String(describing: NDProductDetailView.self))
    }
    
    func getGoAndVerifyButton(title: String) -> some View {
        Group {
            HStack(spacing: 3)  {
                Text(title)
                Image(systemName: "arrow.right")
                    .foregroundColor(Color(hex: "#FFFFFF"))
            }
            .font(.system(size: 14))
            .foregroundColor(Color(hex: "#FFFFFF"))
            .padding(.horizontal, 16)
            .padding(.vertical, 5)
            .background(Color(hex: "#271F24"))
            .clipShape(Capsule())
            .contentShape(Rectangle())
            .padding(.bottom, 10)
            .frame(height: 33)
        }
    }
    
    func getCompletedButton(title: String) -> some View {
        HStack(spacing: 5) {
            Image(systemName: "checkmark.circle.fill")
                .foregroundColor(Color(hex: "#FD632B"))
            HStack {
                Text(title)
            }
        }
        .font(.system(size: 14))
        .foregroundColor(Color(hex: "#FD632B"))
        .padding(.horizontal, 16)
        .padding(.vertical, 5)
        .background(Color(hex: "#FFE7DE"))
        .clipShape(Capsule())
        .contentShape(Rectangle())
        .padding(.bottom, 10)
        .frame(height: 33)
    }
}

extension NDProductDetailView {
    
    func nextStepAction() {
        handleNextStepNavigation(isNotification: false)
    }
    
    func setNextStepNotification() {
        handleNextStepNavigation(isNotification: true)
    }
    
    private func handleNextStepNavigation(isNotification: Bool) {
        guard let nextStep = viewModel.nextStep else {
            if !isNotification {
                postFollowUpNotification()
            }
            return
        }
        
        guard let cernious = nextStep.cernious else {
            return
        }
        
        viewModel.toNavTitle = viewModel.nextStepTitle ?? ""
        
        if let cernious = AuthType(rawValue: cernious) {
            self.goToCorrectVC(with: cernious, isCompleted: false)
        }
    }
    
    private func postFollowUpNotification() {
        NotificationCenter.default.post(
            name: .followUpCurrentProductNotification,
            object: nil,
            userInfo: nil
        )
    }
    
    func goToCorrectVC(with authType: AuthType, isCompleted: Bool) {
        switch authType {
        case .public:
            goToAuthenticationView(isCompleted)
        case .personal:
            goToPersonalView()
        case .contact:
            goToContactsView()
        case .bank:
            goToBankView()
        default:
            break
        }
    }
    
    func goToAuthenticationView(_ isCompleted: Bool) {
        navManager.wrappedValue.pushTitleView(tag: mainNav) {
            NDIDAuthenticationView(title: viewModel.toNavTitle,
                                   orderNum: viewModel.orderNum,
                                   productId: viewModel.currentProductId,
                                   stepType: isCompleted ? .completed : .upload)
        }
    }
    
    func goToPersonalView() {
        navManager.wrappedValue.pushTitleView(tag: mainNav) {
            NDPersonalInfoView(title: viewModel.toNavTitle,
                               productId: viewModel.currentProductId,
                               orderNum: viewModel.orderNum)
        }
    }
    
    func goToContactsView() {
        navManager.wrappedValue.pushTitleView(tag: mainNav) {
            NDContactsView(title: viewModel.toNavTitle,
                           productId: viewModel.currentProductId,
                           orderNum: viewModel.orderNum)
        }
    }
    
    func goToBankView() {
        navManager.wrappedValue.pushTitleView(tag: mainNav) {
            NDBankView(title: viewModel.toNavTitle,
                       productId: viewModel.currentProductId,
                       orderNum: viewModel.orderNum)
        }
    }
    
    func goToWebView(_ urlString: String) {
        
        guard !isWebViewPushing else {
            print("⚠️ 已经在 NDWebView 页面，防止重复 push")
            return
        }
        isWebViewPushing = true
        
        if navManager.wrappedValue.isCurrentView(tag: mainNav, viewType: NDWebView.self) {
            print("⚠️ 已经在 NDWebView 页面，防止重复 push")
            return
        }
        
        let webUrlStr = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
        print("webUrlStr: \(webUrlStr ?? "")")
        navManager.wrappedValue.pushView(tag: mainNav) {
            NDWebView(urlString: webUrlStr,
                      isFollowOrder: true,
                      isPresent: false)
        }
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            isWebViewPushing = false
        }
    }
}
